
package com.proxy.common.pool.impl;


import com.proxy.common.pool.IdleObjectQueue;
import com.proxy.common.pool.PoolObject;
import com.proxy.common.pool.common.PoolConfig;
import com.proxy.common.pool.common.PoolException;

import java.util.Iterator;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;


/**
 * 队列实现类
 * @author liufish
 *
 */
public class BaseIdleObjectQueue<T> implements IdleObjectQueue<T> {
	
	private final ArrayBlockingQueue<PoolObject<T>> idleQueue;
	
	public BaseIdleObjectQueue(PoolConfig config) {
		idleQueue = new ArrayBlockingQueue<PoolObject<T>>(
				config.getMaxActive());
		
	}
	
	@Override
	public PoolObject<T> poll(long timeout, TimeUnit unit){
		try {
			PoolObject<T> idle = idleQueue.poll(timeout,TimeUnit.MILLISECONDS);
			return idle;
		}catch (Exception ex){
			throw new PoolException(ex);
		}
	}

	@Override
	public boolean offer(PoolObject<T> poolObject)  {
		if (poolObject == null){
			throw new PoolException("poolObject is null");
		}

		boolean offerSuccessful = idleQueue.offer(poolObject);
		return offerSuccessful;
	}

	@Override
	public int getIdleObjectsCount() {
		return idleQueue.size();
	}

	@Override
	public void clear() {
		idleQueue.clear();
	}

	@Override
	public PoolObject<T> poll() {
		PoolObject<T> idle = idleQueue.poll();
		return idle;
	}
	@Override
	public void remove(PoolObject<T> poolObject){
		idleQueue.remove(poolObject);
	}

	@Override
	public void iterators(PoolCallback callback){
		Iterator<PoolObject<T>> iterators =  idleQueue.iterator();
		while (iterators.hasNext()){
			PoolObject<T> poolObject = iterators.next();
			callback.call(poolObject);
		}

	}
}
